#include "../include/LHG_XML.h"

void lhg_XMLSettingCreat(const char *path)
{
    xmlDocPtr doc = NULL;
    xmlNodePtr root = NULL;

    doc = xmlNewDoc(BAD_CAST "1.0");
    root = xmlNewNode(NULL, BAD_CAST "Root");
    xmlDocSetRootElement(doc, root);

    xmlNewChild(root, NULL, BAD_CAST "Role", BAD_CAST "NULL");
    xmlNewChild(root, NULL, BAD_CAST "Name", BAD_CAST "NULL");
    xmlNewChild(root, NULL, BAD_CAST "Email", BAD_CAST "NULL");
    xmlNewChild(root, NULL, BAD_CAST "Username", BAD_CAST "NULL");
    xmlNewChild(root, NULL, BAD_CAST "Password", BAD_CAST "NULL");
    xmlNewChild(root, NULL, BAD_CAST "RepoPath", BAD_CAST "NULL");
    xmlNewChild(root, NULL, BAD_CAST "URL", BAD_CAST "NULL");
    xmlNewChild(root, NULL, BAD_CAST "PubKeyPath", BAD_CAST "NULL");
    xmlNewChild(root, NULL, BAD_CAST "PrivKeyPath", BAD_CAST "NULL");

    xmlSaveFormatFileEnc(path, doc, "UTF-8", 1);
    xmlFreeNode(root);
}

void lhg_XMLSettingWrite(const char *path, const char *XMLValue, const char *Value)
{
    xmlDocPtr doc = NULL;
    xmlNodePtr cur = NULL;
    doc = xmlParseFile(path);
    cur = xmlDocGetRootElement(doc);
    cur = cur->xmlChildrenNode;
    while (cur != NULL)
    {
        if (cur->type == XML_ELEMENT_NODE)
        {
            if (!xmlStrcmp(cur->name, (const xmlChar *)XMLValue))
            {
                cur->children->content = (xmlChar *)Value;
            }
        }
        cur = cur->next;
    }
    xmlSaveFormatFile(path, doc, 1);
    xmlFreeNode(cur);
    xmlCleanupParser();
}

void lhg_XMLSettingRead(unsigned char **out, const char *path, const char *XMLReadValue)
{
    xmlDocPtr doc = NULL;
    xmlNodePtr cur = NULL;
    doc = xmlParseFile(path);
    cur = xmlDocGetRootElement(doc);
    cur = cur->xmlChildrenNode;
    while (cur != NULL)
    {
        if ((!xmlStrcmp(cur->name, (const xmlChar *)XMLReadValue)))
        {
            *out = xmlNodeGetContent(cur->children);
        }
        cur = cur->next;
    }
    xmlFreeDoc(doc);
    xmlFreeNode(cur);
    xmlCleanupParser();
}
